// pages/login/login.js
const app = getApp();
let tool = require('../../utils/tool.js');
let util = require('../../utils/util.js');
const log = require('../../utils/log.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageurl: 'https://yxpmaterial.oss-cn-beijing.aliyuncs.com/',
    useInfor: null,
    mobile: '',
    pwd: '',
    hasUserInfo: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("------onLoad-----")
    wx.login({
      success: function (res) {
        if (res.code) {
          app.globalData.code = res.code;
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });
    let that = this;
    // wx.getSetting({
    //   success(res) {
    //     if (res.authSetting['scope.userInfo']) {
    //       wx.getUserInfo({
    //         success: function(res) {
    //           that.setUserInfo(res);
    //         }
    //       })
    //     }
    //   }
    // })
  },

  getUserProfile(e) {
    let that = this;
    console.log("进入getUserProfile()")
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善学员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        this.setData({
          useInfor: res.userInfo,
          hasUserInfo: true
        })
        app.globalData.userInfo = this.data.useInfor;
        that.requestLogin();
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.login({
      success: function (res) {
        if (res.code) {
          app.globalData.code = res.code;
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  phoneChange: function (e) {
    let that = this;
    that.setData({
      mobile: e.detail.value
    })

  },
  pwdChange: function (e) {
    let that = this;
    that.setData({
      pwd: e.detail.value
    })

  },
login:function(){
  if (this.data.useInfor === null) {
    // this.onLoad();
    console.log("userinfo为空")
    this.getUserProfile();
  } else {
    this.requestLogin();
  }
},
  // //节流函数，防止登录按钮快点
  // formSubmit: util.throttle(function (e) {
  //   console.log("进入formsubmit()方法")
  //   let that = this;
  //   that.setData({
  //     mobile: e.detail.value.uname,
  //     pwd: e.detail.value.pwd
  //   })

  //   if (this.data.useInfor === null) {
  //     // this.onLoad();
  //     console.log("userinfo为空")
  //     that.getUserProfile();
  //   } else {
  //     that.requestLogin();
  //   }
  // }, 1500),

  // 请求登录
  requestLogin() {
    let that = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          app.globalData.code = res.code;
        }
      }
    });
    wx.showLoading({
      title: '',
      mask: true
    })
    // name: this.filter(app.globalData.userInfo.nickName),
    let bodyParam = {
      mobile: that.data.mobile,
      code: app.globalData.code,
      password: that.data.pwd,
      type: '1',
      avatar: app.globalData.userInfo.avatarUrl
    }
    let rs = tool.getSign(bodyParam, app.globalData.key); //返回 bodyParam heaer sign
    let urlStr = app.globalData.apiURL + "user/login?sign=" + rs.sign;

    let loginPro = new Promise(function (reslove, reject) {
      wx.request({
        url: urlStr,
        header: rs.header,
        data: rs.bodyParam,
        method: 'post',
        success(res) {
          reslove(res);
        },
        complete: function () {
          wx.hideLoading();
        }
      })

    });
    loginPro.then(function (res) {

      if (res.data.code !== 1) {
        wx.hideLoading();
        setTimeout(function () {
          wx.showToast({
            title: res.data.info,
            icon: 'none',
            duration: 2000
          });
        }, 500)

        if (res.data.code == 10006) {
          //签名错，上传实时日志
          log.error("composeStr为：" + rs.compseStr)
        }

      } else {
        wx.hideLoading();
        app.globalData.studentInfo = res.data.data;
        wx.switchTab({
          url: '../index/index'
        })

      }
    })
  },

  setUserInfo: function (res) {
    console.log("setUserInfo方法")
    this.setData({
      useInfor: res.userInfo
    })
    app.globalData.userInfo = this.data.useInfor;
    wx.showLoading({
      title: '',
      mask: true
    })
    // name: this.filter(app.globalData.userInfo.nickName),
    let bodyParam = {
      mobile: this.data.mobile,
      code: app.globalData.code,
      password: this.data.pwd,
      type: '1',
      avatar: app.globalData.userInfo.avatarUrl
    }
    console.log("----请求登录接口------")
    let rs = tool.getSign(bodyParam, app.globalData.key); //返回 bodyParam heaer sign
    let urlStr = app.globalData.apiURL + "user/login?sign=" + rs.sign;

    let loginPro = new Promise(function (reslove, reject) {
      wx.request({
        url: urlStr,
        header: rs.header,
        data: rs.bodyParam,
        method: 'post',
        success(res) {
          reslove(res);
        },
        complete: function () {
          wx.hideLoading();
        }
      })
    });
    loginPro.then(function (res) {
      if (res.data.code !== 1) {
        wx.hideLoading();
      } else {
        wx.hideLoading();
        app.globalData.studentInfo = res.data.data;
        wx.switchTab({
          url: '../index/index'
        })

      }
    })

  },


  filter: function (str) {
    let names = str;
    let returnstr = '';
    if (str) {
      names = str;
      // names = names.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
      names = names.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]|\uD83E[\udd00-\udfff]|[\u2600-\u27ff]/g, "*");
      returnstr = names;
      if (!returnstr) {
        return returnstr;
      }
    } else {
      returnstr = '';
    }
    return returnstr;
  }

})